const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs').promises;
const db = require('../config/db');

const router = express.Router();

// 配置文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 确保上传目录存在
    const uploadDir = path.join(__dirname, '../../uploads');
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 更完善的中文文件名处理
    let originalname = file.originalname;
    
    // 尝试修复可能的编码问题
    try {
      // 尝试解码可能被错误编码的文件名
      const decodedName = decodeURIComponent(escape(originalname));
      originalname = decodedName;
    } catch (e) {
      // 如果解码失败，保持原始文件名
      console.warn('文件名解码警告:', e.message);
    }
    
    // 移除路径部分，只保留文件名
    originalname = originalname.replace(/\\/g, '/').split('/').pop();
    
    // 生成唯一文件名，保留原始扩展名
    const ext = path.extname(originalname);
    const basename = path.basename(originalname, ext);
    
    // 使用时间戳和随机数生成唯一文件名
    const timestamp = Date.now();
    const randomNum = Math.round(Math.random() * 1E9);
    const filename = `${basename}-${timestamp}-${randomNum}${ext}`;
    cb(null, filename);
  }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 接受所有文件类型
  cb(null, true);
};

const upload = multer({ 
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 10 * 1024 * 1024 // 限制文件大小为10MB
  },
  preservePath: true
});

// 确保上传目录存在
const ensureUploadDir = async () => {
  const uploadDir = path.join(__dirname, '../../uploads');
  try {
    await fs.access(uploadDir);
  } catch {
    await fs.mkdir(uploadDir, { recursive: true });
  }
};

// 初始化上传目录
ensureUploadDir();

// 获取文件列表
router.get('/files', async (req, res) => {
  try {
    const { page = 1, pageSize = 10, name, type } = req.query;
    const offset = (page - 1) * pageSize;
    
    // 普通用户只能看到自己上传的文件，管理员可以看到所有文件
    let query = 'SELECT id, name, original_name, size, type, url, uploader_id, uploader_name, created_at FROM files WHERE 1=1';
    let countQuery = 'SELECT COUNT(*) as total FROM files WHERE 1=1';
    const params = [];
    
    // 如果是普通用户，只查询自己上传的文件
    if (req.user && req.user.role === 'user') {
      query += ' AND uploader_id = ?';
      countQuery += ' AND uploader_id = ?';
      params.push(req.user.id);
    }
    
    if (name) {
      query += ' AND original_name LIKE ?';
      countQuery += ' AND original_name LIKE ?';
      params.push(`%${name}%`);
    }
    
    if (type) {
      // 根据前端传递的简化类型转换为实际的MIME类型进行筛选
      let mimeType = '';
      switch (type) {
        case 'image':
          mimeType = 'image/%';
          query += ' AND type LIKE ?';
          countQuery += ' AND type LIKE ?';
          params.push(mimeType);
          break;
        case 'document':
          // 文档类型包括文本、PDF、Word、Excel等
          query += ' AND (type LIKE "text/%" OR type = "application/pdf" OR type LIKE "application/msword" OR type LIKE "application/vnd.openxmlformats-officedocument%")';
          countQuery += ' AND (type LIKE "text/%" OR type = "application/pdf" OR type LIKE "application/msword" OR type LIKE "application/vnd.openxmlformats-officedocument%")';
          break;
        case 'video':
          mimeType = 'video/%';
          query += ' AND type LIKE ?';
          countQuery += ' AND type LIKE ?';
          params.push(mimeType);
          break;
        case 'audio':
          mimeType = 'audio/%';
          query += ' AND type LIKE ?';
          countQuery += ' AND type LIKE ?';
          params.push(mimeType);
          break;
        case 'other':
          // 其他类型排除上述类型
          query += ' AND type NOT LIKE "image/%" AND type NOT LIKE "video/%" AND type NOT LIKE "audio/%" AND type NOT LIKE "text/%" AND type != "application/pdf" AND type NOT LIKE "application/msword" AND type NOT LIKE "application/vnd.openxmlformats-officedocument%"';
          countQuery += ' AND type NOT LIKE "image/%" AND type NOT LIKE "video/%" AND type NOT LIKE "audio/%" AND type NOT LIKE "text/%" AND type != "application/pdf" AND type NOT LIKE "application/msword" AND type NOT LIKE "application/vnd.openxmlformats-officedocument%"';
          break;
        default:
          query += ' AND type = ?';
          countQuery += ' AND type = ?';
          params.push(type);
      }
    }
    
    query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
    params.push(parseInt(pageSize));
    params.push(parseInt(offset));
    
    const [rows] = await db.execute(query, params);
    const [countResult] = await db.execute(countQuery, params.slice(0, -2));
    const total = countResult[0].total;
    
    res.json({
      code: 200,
      message: '获取文件列表成功',
      data: {
        list: rows,
        pagination: {
          currentPage: parseInt(page),
          pageSize: parseInt(pageSize),
          total: total
        }
      }
    });
  } catch (error) {
    console.error('获取文件列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 上传文件
router.post('/files', upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        code: 400,
        message: '请选择要上传的文件'
      });
    }
    
    // 获取文件信息
    let { originalname, filename, size, mimetype } = req.file;
    
    // 更完善的文件名编码处理
    // 处理可能的乱码问题
    try {
      // 尝试解码可能被错误编码的文件名
      const decodedName = decodeURIComponent(escape(originalname));
      originalname = decodedName;
    } catch (e) {
      // 如果解码失败，保持原始文件名
      console.warn('文件名解码警告:', e.message);
    }
    
    // 处理Content-Disposition头中的UTF-8文件名
    if (req.headers['content-disposition']) {
      const contentDisposition = req.headers['content-disposition'];
      
      // 匹配 filename*=UTF-8'' 格式
      const utf8FilenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)$/i);
      if (utf8FilenameMatch) {
        try {
          originalname = decodeURIComponent(utf8FilenameMatch[1]);
        } catch (decodeError) {
          console.warn('UTF-8文件名解码失败:', decodeError);
        }
      } else {
        // 匹配 filename="" 格式
        const filenameMatch = contentDisposition.match(/filename="(.+?)"/i);
        if (filenameMatch) {
          try {
            originalname = filenameMatch[1];
            
            // 尝试处理可能的编码问题
            try {
              const decodedName = decodeURIComponent(escape(originalname));
              originalname = decodedName;
            } catch (e) {
              // 如果解码失败，保持原始文件名
              console.warn('文件名二次解码警告:', e.message);
            }
          } catch (decodeError) {
            console.warn('文件名解码失败:', decodeError);
          }
        }
      }
    }
    
    const filePath = `/uploads/${filename}`;
    const fileUrl = `${req.protocol}://${req.get('host')}${filePath}`;
    
    // 插入数据库
    const [result] = await db.execute(
      'INSERT INTO files (name, original_name, size, type, path, url, uploader_id, uploader_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
      [filename, originalname, size, mimetype, filePath, fileUrl, req.user?.id || null, req.user?.name || req.user?.account || '未知用户']
    );
    
    res.status(201).json({
      code: 201,
      message: '文件上传成功',
      data: {
        id: result.insertId,
        name: filename,
        originalName: originalname,
        size: size,
        type: mimetype,
        url: fileUrl,
        createdAt: new Date()
      }
    });
  } catch (error) {
    console.error('文件上传失败:', error);
    res.status(500).json({
      code: 500,
      message: '文件上传失败'
    });
  }
});

// 删除文件
router.delete('/files/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    // 查询文件信息
    const [rows] = await db.execute('SELECT * FROM files WHERE id = ?', [id]);
    
    if (rows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '文件不存在'
      });
    }
    
    const file = rows[0];
    
    // 从数据库删除记录
    await db.execute('DELETE FROM files WHERE id = ?', [id]);
    
    // 从文件系统删除文件
    try {
      const fullPath = path.join(__dirname, '../..', file.path);
      await fs.unlink(fullPath);
    } catch (fsError) {
      console.warn('删除文件失败:', fsError);
    }
    
    res.json({
      code: 200,
      message: '文件删除成功'
    });
  } catch (error) {
    console.error('删除文件失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 批量删除文件
router.delete('/files', async (req, res) => {
  try {
    const { ids } = req.body;
    
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        code: 400,
        message: '请选择要删除的文件'
      });
    }
    
    // 查询文件信息
    const placeholders = ids.map(() => '?').join(',');
    const [rows] = await db.execute(`SELECT * FROM files WHERE id IN (${placeholders})`, ids);
    
    // 从数据库删除记录
    await db.execute(`DELETE FROM files WHERE id IN (${placeholders})`, ids);
    
    // 从文件系统删除文件
    for (const file of rows) {
      try {
        const fullPath = path.join(__dirname, '../..', file.path);
        await fs.unlink(fullPath);
      } catch (fsError) {
        console.warn('删除文件失败:', fsError);
      }
    }
    
    res.json({
      code: 200,
      message: `成功删除${rows.length}个文件`
    });
  } catch (error) {
    console.error('批量删除文件失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

module.exports = router;